package sns.app.shoot3d;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import org.apache.catalina.websocket.MessageInbound;

public class Shoot3DMessageInbound extends MessageInbound {

	private int cid;
	private ArrayList<Shoot3DMessageInbound> connections;
	
	public Shoot3DMessageInbound(int cid, ArrayList<Shoot3DMessageInbound> connections){
		this.setCid(cid);
		connections.add(this);
		this.connections = connections;
	}
	
	protected void onClose(int status) {
		connections.remove(this);
	}

	@Override
	protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
	}
	
	@Override
	protected void onTextMessage(CharBuffer message) throws IOException {
		broadcast(message.toString(), connections);
		System.out.println(message.toString());
	}
	
	public void broadcast(String message,
			ArrayList<Shoot3DMessageInbound> connections) {
		for (Shoot3DMessageInbound connection : connections) {
			if(connection.cid!=this.cid){
				sendMessageTo(message, connection);
			}
		}
	}
	
	public void sendMessageTo(String message,
			Shoot3DMessageInbound connection) {
		try {
			CharBuffer buffer = CharBuffer.wrap(message);
			connection.getWsOutbound().writeTextMessage(buffer);
		} catch (IOException ignore) {
			// Ignore
		}
	}

	public int getCid() {
		return cid;
	}

	public void setCid(int cid) {
		this.cid = cid;
	}
	
}
